package com.th.admin.controller.system;


import cn.hutool.core.io.IoUtil;
import com.th.common.core.controller.BaseController;
import com.th.common.core.domain.AjaxResult;
import com.th.common.core.page.TableDataInfo;
import com.th.system.domain.SysCarousel;
import com.th.system.service.ISysCarouselService;
import com.th.system.service.SysFileService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 轮播图(走马灯) 前端控制器
 * </p>
 *
 * @author tuhang
 * @since 2022-05-16
 */
@Api(tags = {"轮播图(走马灯) 前端控制器"})
@RestController
@RequestMapping("/admin/system/sys-carousel")
public class SysCarouselAdminController extends BaseController {

    @Autowired
    private ISysCarouselService sysCarouselService;

    @Resource
    private SysFileService sysFileService;

    /**
     * 查询轮播图(走马灯)列表
     */
    @PreAuthorize("@ss.hasPermi('system:sys-carousel:list')")
    @GetMapping("/list")
    public TableDataInfo list() {
        List<SysCarousel> list = sysCarouselService.selectSortedSysCarouselList();
        return getDataTable(list);
    }

    /**
     * 获取轮播图(走马灯)详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:sys-carousel:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        return AjaxResult.success(sysCarouselService.getById(id));
    }

    /**
     * 新增轮播图(走马灯)
     */
    @PreAuthorize("@ss.hasPermi('system:sys-carousel:add')")
    @PostMapping
    public AjaxResult add(@RequestBody SysCarousel sysCarousel) {
        return toAjax(sysCarouselService.save(sysCarousel));
    }



    /**
     * 上传轮播图
     */
    @PreAuthorize("@ss.hasPermi('system:sys-carousel:upload')")
    @PostMapping("/upload")
    public AjaxResult upload(@RequestPart("file") MultipartFile file) {
        try {
            String path = sysFileService.createFile(file.getOriginalFilename(), IoUtil.readBytes(file.getInputStream()));
            return AjaxResult.success().put("path", path);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }


    /**
     * 修改轮播图(走马灯)
     */
    @PreAuthorize("@ss.hasPermi('system:sys-carousel:edit')")
    @PutMapping
    public AjaxResult edit(@RequestBody SysCarousel sysCarousel) {
        return toAjax(sysCarouselService.updateById(sysCarousel));
    }

    /**
     * 删除轮播图(走马灯)
     */
    @PreAuthorize("@ss.hasPermi('system:carousel:remove')")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        return toAjax(sysCarouselService.removeByIds(Arrays.asList(ids)));
    }
}
